<template>
  <div class="search-result-container">
    <!-- 点击实现后退效果 -->
    <van-nav-bar
      title="搜索结果"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <van-list
      v-model="loading"
      @load="onLoad"
      offset="18"
      :finished="finished"
      finished-text="没有更多了"
      :immediate-check="false"
    >
      <!-- .native 能够给组件绑定原生对象的事件 -->
      <ListItem
        v-for="item in searchList"
        :key="item.id"
        :title="item.title"
        :author="item.aut_name"
        :cmt-count="item.comm_count"
        :time="item.pubdate"
        :cover="item.cover"
        @click.native="openDetail(item.art_id)"
      ></ListItem>
    </van-list>
  </div>
</template>

<script>
import ListItem from '@/components/ListItem/ListItem.vue'
import { getSearchResult } from '@/api/request.js'
export default {
  name: 'SearchResult',
  beforeRouteLeave(to, from, next) {
    from.meta.top = window.scrollY
    setTimeout(() => {
      next()
    }, 0)
  },
  data() {
    return {
      // 页码值
      page: 1,
      // 搜索的结果
      searchList: [],
      // 是否正在进行上拉加载的数据请求
      loading: false,
      // 所有数据是否已经加载完毕
      finished: false,
    }
  },
  components: {
    ListItem,
  },
  created() {
    this.getSearchResult()
  },
  methods: {
    // 获取搜索文章的数据
    async getSearchResult() {
      const params = {
        q: this.$route.params.kw,
        page: this.page,
      }
      const { data: res } = await getSearchResult(params)
      // console.log(res);
      const { message, data } = res
      if (message !== 'OK') {
        return this.$notify({ type: 'danger', message: '获取搜索文章失败' })
      }
      this.searchList = [...this.searchList, ...data.results]
      this.loading = false
      // 判断数据是否加载完毕
      if (res.data.results.length === 0) {
        this.finished = true
      }
      // 让页码值 +1
      this.page += 1
    },
    // 打开详情页
    openDetail(id) {
      // console.log(id);
      // this.$router.push(`/detail/${id}`);
      this.$toast('抱歉, 搜索暂不支持进入详情页')
    },
    // 上拉加载
    onLoad() {
      this.getSearchResult()
    },
  },
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;

  /deep/.van-nav-bar {
    .van-icon {
      color: #fff;
    }
  }
}
</style>
